<template>
  <div class="option-wrapper">
    <div class="option-main">
      <a-form layout="vertical" :model="formState" :rules="rules" ref="formRef">
        <div class="option-column">
          <div class="column-title">基础信息</div>
          <div class="column-content">
            <div class="content-item">
              <a-form-item label="名称" name="name">
                <a-input
                  v-model:value="formState.name"
                  placeholder="请输入策略名称"
                />
              </a-form-item>
            </div>
            <div class="content-item">
              <a-form-item label="描述" name="description">
                <a-textarea
                  v-model:value="formState.description"
                  placeholder="请输入策略描述"
                  :rows="3"
                />
              </a-form-item>
            </div>
            <div class="content-item">
              <a-form-item label="启用状态" name="enabled">
                <a-select
                  v-model:value="formState.enabled"
                  placeholder="请选择状态"
                >
                  <a-select-option :value="true">启用</a-select-option>
                  <a-select-option :value="false">禁用</a-select-option>
                </a-select>
              </a-form-item>
            </div>
            <div class="content-item">
              <a-form-item label="排序" name="sort">
                <a-input-number
                  v-model:value="formState.sort"
                  placeholder="请输入排序值"
                  :min="0"
                  style="width: 100%"
                />
              </a-form-item>
            </div>
          </div>

          <div class="option-column">
            <div class="column-title">会员定价</div>
            <div class="column-content">
              <div class="content-item">
                <a-form-item label="年费（￥）" name="annual_fee">
                  <a-input-number
                    v-model:value="formState.annual_fee"
                    placeholder="请输入年费金额"
                    :min="0"
                    :precision="2"
                    style="width: 100%"
                  />
                </a-form-item>
              </div>
            </div>
          </div>

          <div class="option-column">
            <div class="column-title">AI服务</div>
            <div class="column-content">
              <div class="content-item">
                <a-form-item label="AI实验助手" name="ai_enabled">
                  <a-select
                    v-model:value="formState.ai_enabled"
                    placeholder="请选择状态"
                  >
                    <a-select-option :value="true">开通</a-select-option>
                    <a-select-option :value="false">关闭</a-select-option>
                  </a-select>
                </a-form-item>
              </div>
              <div class="content-item">
                <a-form-item label="会员每日免费Token" name="tokens_for_member">
                  <a-input-number
                    v-model:value="formState.tokens_for_member"
                    placeholder="请输入会员每日免费Token数量"
                    :min="0"
                    style="width: 100%"
                  />
                </a-form-item>
              </div>
              <div class="content-item">
                <a-form-item
                  label="非会员每日免费Token"
                  name="tokens_non_member"
                >
                  <a-input-number
                    v-model:value="formState.tokens_non_member"
                    placeholder="请输入非会员每日免费Token数量"
                    :min="0"
                    style="width: 100%"
                  />
                </a-form-item>
              </div>
            </div>
          </div>

          <div class="option-column">
            <div class="column-title">备注信息</div>
            <div class="column-content">
              <div class="content-item">
                <a-form-item label="备注" name="remark">
                  <a-textarea
                    v-model:value="formState.remark"
                    placeholder="请输入备注信息"
                    :rows="3"
                  />
                </a-form-item>
              </div>
            </div>
          </div>

          <div class="option-column">
            <div class="column-title">实验资源策略</div>
            <a-table
              class="table-inner"
              :columns="columns"
              :data-source="tableData"
              :pagination="{
                total: tableData.length,
                current: 1,
                pageSize: 10,
                hideOnSinglePage: true,
              }"
            >
              <template #bodyCell="{ column, record, index }">
                <template v-if="column.dataIndex === 'member_only'">
                  <a-select
                    v-model:value="record.member_only"
                    placeholder="请选择"
                    style="width: 100%"
                    @change="handleMemberOnlyChange(record, index)"
                  >
                    <a-select-option :value="true">是</a-select-option>
                    <a-select-option :value="false">否</a-select-option>
                  </a-select>
                </template>
                <template v-if="column.dataIndex === 'free_amount_non_member'">
                  <a-input-number
                    v-model:value="record.free_amount_non_member"
                    :disabled="record.member_only === true"
                    :min="0"
                    style="width: 100%"
                    placeholder="免费次数"
                  />
                </template>
                <template v-if="column.dataIndex === 'sort'">
                  <a-input-number
                    v-model:value="record.sort"
                    :min="0"
                    style="width: 100%"
                    placeholder="排序"
                  />
                </template>
              </template>
            </a-table>
          </div>
        </div>

        <div class="option-footer">
          <a-button class="opt-btn" @click="resetForm">取消</a-button>
          <a-button
            class="opt-btn"
            type="primary"
            :loading="saveLoading"
            @click="save"
            >保存</a-button
          >
        </div>
      </a-form>
    </div>
  </div>
</template>
<script setup>
import API from "@/api/administrator";
import { message } from "ant-design-vue";
import { onMounted, reactive, ref } from "vue";
import { useRoute, useRouter } from "vue-router";

const route = useRoute();
const router = useRouter();

// 表单引用
const formRef = ref();
const saveLoading = ref(false);

// 判断是编辑还是新增
const isEdit = ref(false);
const strategyId = ref(null);

// 表单数据
const formState = reactive({
  strategy_id: null,
  name: "",
  description: "",
  annual_fee: 0,
  ai_enabled: true,
  tokens_non_member: 0,
  tokens_for_member: 0,
  remark: "",
  sort: 0,
  enabled: true,
});

// 表格列定义
const columns = ref([
  // {
  //   title: '实验ID',
  //   dataIndex: 'experiment_id',
  //   key: 'experiment_id',
  //   width: 100,
  // },
  {
    title: "实验名称",
    dataIndex: "experiment_name",
    key: "experiment_name",
    width: 200,
  },
  {
    title: "仅会员",
    dataIndex: "member_only",
    key: "member_only",
    width: 120,
  },
  {
    title: "非会员免费次数",
    dataIndex: "free_amount_non_member",
    key: "free_amount_non_member",
    width: 150,
  },
  {
    title: "排序",
    dataIndex: "sort",
    key: "sort",
    width: 80,
  },
]);

// 实验策略数据
const tableData = ref([]);

// 表单验证规则
const rules = ref({
  name: [
    {
      required: true,
      message: "请输入策略名称",
      trigger: "blur",
    },
  ],
  annual_fee: [
    {
      required: true,
      message: "请输入年费金额",
      trigger: "blur",
    },
  ],
  enabled: [
    {
      required: true,
      message: "请选择启用状态",
      trigger: "change",
    },
    // { type: "number", message: "启用状态必须为数字", trigger: "change" },
  ],
});

// 初始化页面数据
const initPageData = async () => {
  // 从路由参数获取strategy_id
  const routeStrategyId = route.query.strategy_id || route.params.strategy_id;

  if (routeStrategyId) {
    isEdit.value = true;
    strategyId.value = routeStrategyId;
    await loadStrategyData(routeStrategyId);
  } else {
    // 新增模式，加载实验列表用于配置
    await loadExperimentOptions();
  }
};

// 加载策略数据（编辑模式）
const loadStrategyData = async (id) => {
  try {
    const response = await API.MembershipStrategyFetchModel({
      strategy_id: id,
    });
    console.log("API返回结果:", response);

    if (response) {
      const data = response;
      console.log("获取到的策略数据:", data);

      // 填充表单数据
      Object.assign(formState, {
        strategy_id: data.strategy_id,
        name: data.name || "",
        description: data.description || "",
        annual_fee: data.annual_fee || 0,
        // ai_enabled: data.ai_enabled ? 1 : 0,
        tokens_non_member: data.tokens_non_member || 0,
        tokens_for_member: data.tokens_for_member || 0,
        remark: data.remark || "",
        sort: data.sort || 0,
        // enabled: data.enabled ? 1 : 0,
      });

      // 填充实验策略表格数据
      tableData.value = (data.membership_strategy_experiments || []).map(
        (item, index) => ({
          key: index,
          experiment_id: item.experiment_id,
          experiment_name: item.experiment?.name || `实验${index + 1}`,
          member_only: item.member_only,
          free_amount_non_member: item.free_amount_non_member || 0,
          sort: item.sort || 0,
          strategy_id: item.strategy_id,
          remark: item.remark || "",
          // 保存完整的experiment对象，用于提交时保持数据完整性
          experiment: item.experiment || null,
        })
      );

      console.log("填充后的表单数据:", formState);
      console.log("填充后的表格数据:", tableData.value);
    } else {
      console.error("API调用失败或数据格式错误:", response);
      message.error("加载策略数据失败");
    }
  } catch (error) {
    console.error("加载策略数据失败:", error);
    message.error("加载策略数据失败");
  }
};

// 加载实验选项（新增模式）
const loadExperimentOptions = async () => {
  try {
    // 这里可以调用获取实验列表的API
    // 暂时使用模拟数据
    tableData.value = [
      {
        key: 1,
        experiment_id: 1,
        experiment_name: "AI文本生成实验",
        member_only: true,
        free_amount_non_member: 5,
      },
      {
        key: 2,
        experiment_id: 2,
        experiment_name: "AI图像识别实验",
        member_only: true,
        free_amount_non_member: 3,
      },
      {
        key: 3,
        experiment_id: 3,
        experiment_name: "AI语音合成实验",
        member_only: true,
        free_amount_non_member: 0,
      },
    ];
  } catch (error) {
    console.error("加载实验选项失败:", error);
  }
};

// 重置表单
const resetForm = () => {
  Object.assign(formState, {
    strategy_id: null,
    name: "",
    description: "",
    annual_fee: 0,
    ai_enabled: true,
    tokens_non_member: 0,
    tokens_for_member: 0,
    remark: "",
    sort: 0,
    enabled: true,
  });
  router.back();
};

// 保存策略
const save = async () => {
  try {
    // 表单验证
    await formRef.value.validate();

    saveLoading.value = true;

    // 准备提交数据
    const submitData = {
      ...formState,
      membership_strategy_experiments: tableData.value.map((item) => ({
        strategy_id: formState.strategy_id,
        experiment_id: item.experiment_id,
        member_only: item.member_only,
        free_amount_non_member: item.free_amount_non_member || 0,
        sort: item.sort || 0,
        remark: item.remark || null,
        // 包含完整的experiment对象，保持与API返回数据结构一致
        experiment: item.experiment || null,
      })),
    };
    console.log("🚀 ~ save ~ submitData:", submitData);

    console.log("提交的数据结构:", JSON.stringify(submitData, null, 2));
    console.log(
      "membership_strategy_experiments 数据:",
      submitData.membership_strategy_experiments
    );

    let response;
    if (isEdit.value) {
      // 编辑模式 - 调用更新接口
      response = await API.MembershipStrategyUpdate(submitData);
    } else {
      // 新增模式 - 调用创建接口
      response = await API.MembershipStrategyCreate(submitData);
    }
    console.log("🚀 ~ save ~ response:", response);

    if (response) {
      message.success(isEdit.value ? "策略更新成功" : "策略创建成功");
      router.go(-1);
    } else {
      message.error(response.message || "操作失败");
    }
  } catch (error) {
    console.error("保存失败:", error);
    if (error.errorFields) {
      message.error("请检查表单填写是否正确");
    } else {
      message.error("保存失败，请稍后重试");
    }
  } finally {
    saveLoading.value = false;
  }
};

// 处理仅会员选项变化
const handleMemberOnlyChange = (record, index) => {
  if (record.member_only ) {
    // 如果设置为仅会员，则非会员免费次数设为0
    record.free_amount_non_member = 0;
  }
};

// 页面挂载时初始化数据
onMounted(() => {
  initPageData();
});
</script>
